package com.yl.order.utils;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.TextUtils;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

import java.util.Hashtable;
import java.util.Map;

/**
 * create by cjx on 2024/6/12
 * desc:
 */
public class QRUtils {
    /**
     * 生成简单二维码
     */
    public static void createQRCodeBitmap(ImageView imageView, String content) {
        // 字符串内容判空
        if (TextUtils.isEmpty(content)) {
            return;
        }
        // 宽和高>=0
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        if (width < 0 || height < 0) {
            return;
        }
        try {
            /** 1.设置二维码相关配置 */
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();
            // 字符转码格式设置
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 容错率设置
            hints.put(EncodeHintType.ERROR_CORRECTION, "H");
            // 空白边距设置
            hints.put(EncodeHintType.MARGIN, "0");

            /** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
            MyQRCodeWriter myQRCodeWriter = new MyQRCodeWriter();
            BitMatrix bitMatrix = myQRCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            /** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
            int[] pixels = new int[width * height];
            // 找到二维码的实际边界
            int left = width, top = height, right = 0, bottom = 0;
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    //bitMatrix.get(x,y)方法返回true是黑色色块，false是白色色块
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = Color.BLACK;//黑色色块像素设置
                        if (x < left) {
                            left = x;
                        }
                        if (x > right) {
                            right = x;
                        }
                        if (y < top) {
                            top = y;
                        }
                        if (y > bottom) {
                            bottom = y;
                        }
                    } else {
                        pixels[y * width + x] = Color.WHITE;// 白色色块像素设置
                    }
                }
            }

            /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            Bitmap result = Bitmap.createBitmap(bitmap, left, top, right - left + 1, bottom - top + 1);
            imageView.setImageBitmap(result);
        } catch (WriterException e) {
            e.printStackTrace();
            return;
        }
    }

    static class MyQRCodeWriter implements Writer {

        private static final int QUIET_ZONE_SIZE = 4;
        public int leftPadding = 0;
        public int topPadding = 0;

        @Override
        public BitMatrix encode(String contents, BarcodeFormat format, int width, int height)
                throws WriterException {

            return encode(contents, format, width, height, null);
        }

        @Override
        public BitMatrix encode(String contents,
                                BarcodeFormat format,
                                int width,
                                int height,
                                Map<EncodeHintType, ?> hints) throws WriterException {

            if (contents.isEmpty()) {
                throw new IllegalArgumentException("Found empty contents");
            }

            if (format != BarcodeFormat.QR_CODE) {
                throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);
            }

            if (width < 0 || height < 0) {
                throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' +
                        height);
            }

            ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
            int quietZone = QUIET_ZONE_SIZE;
            if (hints != null) {
                if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
                    errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
                }
                if (hints.containsKey(EncodeHintType.MARGIN)) {
                    quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
                }
            }

            QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints);
            return renderResult(code, width, height, quietZone);
        }

        // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses
        // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).
        private BitMatrix renderResult(QRCode code, int width, int height, int quietZone) {
            ByteMatrix input = code.getMatrix();
            if (input == null) {
                throw new IllegalStateException();
            }
            int inputWidth = input.getWidth();
            int inputHeight = input.getHeight();
            int qrWidth = inputWidth + (quietZone * 2);
            int qrHeight = inputHeight + (quietZone * 2);
            int outputWidth = Math.max(width, qrWidth);
            int outputHeight = Math.max(height, qrHeight);

            int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight);
            // Padding includes both the quiet zone and the extra white pixels to accommodate the requested
            // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.
            // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will
            // handle all the padding from 100x100 (the actual QR) up to 200x160.
            leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
            topPadding = (outputHeight - (inputHeight * multiple)) / 2;

            BitMatrix output = new BitMatrix(outputWidth, outputHeight);

            for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
                // Write the contents of this row of the barcode
                for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
                    if (input.get(inputX, inputY) == 1) {
                        output.setRegion(outputX, outputY, multiple, multiple);
                    }
                }
            }

            return output;
        }

    }

}
